package com.lw.lock;

/**
 * @author LW
 * @2020/8/22 10:49
 */

import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantLock;

/**自旋锁
 * 不断尝试，成功为止
 */
public class SpinLockDemo {
    //int 0
    //Thread null
    AtomicReference<Thread> atomicReference = new AtomicReference<>();

    //加锁
    public void myLock(){
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName()+"==>myLock");
        //自旋锁
        while (atomicReference.compareAndSet(null,thread)){

        }
    }
    //加锁
    public void myUnLock(){
        Thread thread = Thread.currentThread();
        System.out.println(Thread.currentThread().getName()+"==>myUnLock");
        //自旋锁
        atomicReference.compareAndSet(thread,null);
    }



}
class Test{
    public static void main(String[] args) throws InterruptedException {
//        ReentrantLock lock = new ReentrantLock();
//        lock.lock();
//        lock.unlock();

        /**
         * t1-->null-->thread
         * t2等待t1   thread--->null
         */
        SpinLockDemo spinLock = new SpinLockDemo();
        new Thread(()->{
            spinLock.myLock();
            try {
                Thread.sleep(3000);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
            spinLock.myUnLock();
            }

        },"t1").start();

        Thread.sleep(1000);

        new Thread(()->{
            spinLock.myLock();
            try {//t2自旋等t1释放，必须等待
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                spinLock.myUnLock();
            }
        },"t2").start();
        //底层使用的自旋锁CAS


    }
}
